﻿Imports ADOEntity
Imports System.Data
Imports System.Globalization

Partial Class Administrator_SanctionHistory
    Inherits Web.UI.BasePage
    Dim SanctionEntity As SanctionEntities
    Dim dsMaster As New DataSet
    Dim clsQuery As clsDatabase
    Dim clsDataTable As New clsLINQToDataTable
    Dim intBeforeItemIndex As Integer
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim strMsg As String = ""
    Dim clsFormatDate As clsDateFormat
    Dim clsDatabase As New clsDatabase

#Region " Even Page "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

        lblNo.Text = "ครั้งที่อัพเดตข้อมูล"
        lblSource.Text = "แหล่งข้อมูล"
        'lblType.Text = "ประเภท"

        btnSearch.Text = Resources.resButton.btnSearch
        btnClear.Text = Resources.resButton.btnClear
        btnPrint.Text = Resources.resButton.btnPrint

        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            clsSessionMenuRight = Session("clsMenuRight")


            If (Not IsPostBack) Then
                'IsDataBind()
                CreateControlMP()
                loadDataToDropDown()
            Else
                dsMaster = Session("dsTblMaster")
                grdIndividual.DataSource = dsMaster.Tables("dsMaster")
                grdIndividual.DataBind()
            End If
        Catch ex As Exception

        End Try


    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dsMaster
    End Sub

#End Region

#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "Sanction > ประวัติรายชื่อ Sanction List"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Try
            grdIndividual.DataSource = Nothing
            grdIndividual.DataBind()
            IsDataBind()
            SaveLog(1)
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        clear()
    End Sub

    Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click

        Dim param As String
        If Not (chkLookDetail.Checked) Then
            param = "{ 'rptType' : '301'," _
                                         & "'lastUpdateDate' : '" & ddlNo.SelectedValue & ";" & ddlNo.SelectedItem.Text & "'," _
                                         & "'ShowDetail' : '0'," _
                                          & "'datasource' : '" & ddlSource.SelectedValue & "|" & ddlSource.SelectedItem.Text & "'}"
        Else
            param = "{ 'rptType' : '301'," _
                                      & "'lastUpdateDate' : '" & ddlNo.SelectedValue & ";" & ddlNo.SelectedItem.Text & "'," _
                                      & "'ShowDetail' : '1'," _
                                       & "'datasource' : '" & ddlSource.SelectedValue & "|" & ddlSource.SelectedItem.Text & "'}"
        End If


        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType, "key", "OpenWindowWithPost('../Form/frmPrintRptMaster.aspx','width=730,height=345,left=100,top=100,resizable=yes,scrollbars=yes','Report', " + param + ");", True)
        SaveLog(2)

    End Sub

#End Region

#Region "Even GridView"

    Protected Sub grdIndividual_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdIndividual.PageIndexChanging
        grdIndividual.PageIndex = e.NewPageIndex
        clearGvIndex()
        DataBind()
    End Sub

    Protected Sub grdIndividual_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdIndividual.RowDataBound
        Try
            If (e.Row.RowType.ToString = "DataRow") Then
                Dim lblUpdateDate As Label = CType(e.Row.FindControl("lblUpdateDate"), Label)
                If Not (lblUpdateDate.Text = "") Then
                    Dim dteUpdateDate As Date = lblUpdateDate.Text

                    clsFormatDate = New clsDateFormat
                    lblUpdateDate.Text = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.Th, lblUpdateDate.Text) & " " & dteUpdateDate.ToLongTimeString

                    clsFormatDate = Nothing
                End If
            End If
        Catch ex As Exception
            WriteError(ex, "grdIndividual_RowDataBound", "SanctionHistory")
        End Try

    End Sub

    Protected Sub grdIndividual_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdIndividual.Sorting
        Dim dt = TryCast(dsMaster.Tables("dsMaster"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            grdIndividual.DataSource = dsMaster.Tables("dsMaster")
            grdIndividual.DataBind()
            clearGvIndex()
        End If
    End Sub

#End Region

#Region " Function"

    Private Sub loadDataToDropDown()
        Try
            Dim clsDropDown As New clsMasterDropDown
            clsDropDown.setSource(ddlSource)
            clsDropDown = Nothing
        Catch ex As Exception
            WriteError(ex, "loadDataToDropDown", "SanctionHistory")
            Throw ex
        End Try
    End Sub

    Private Sub clearGvIndex()
        grdIndividual.SelectedIndex = -1
        '  btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()
        Try

            SanctionEntity = New SanctionEntities

            Dim sanctionALL As New ADOEntitySanctionList.SanctionListEntities

            If dsMaster.Tables.Contains("dsMaster") Then
                dsMaster.Tables.Clear()
            End If

            Dim qry2 = (From im In sanctionALL.AMLO_NEW_IMPORT_TEMP
                        Group Join m In sanctionALL.AMLO_NEW_MASTER_TEMP On
                        im.IMPORTID Equals m.IMPORTID Into grp1 = Group
                        From g1 In grp1 Order By g1.INFO_SOURCE
                        Select New With {
                            .DATASOURCE = g1.INFO_SOURCE,
                            im.IMPORT_DATE,
                            im.IMPORTID,
                            im.FILE_TYPE,
                            .LASTUPDATEDATE = ""
                                    }).Distinct


            'Dim qry = From m In SanctionEntity.AMLLIST_HIST Group m By m.LASTUPDATEDATE, m.DATASOURCE Into Group
            '          Order By DATASOURCE, LASTUPDATEDATE
            '           Select DATASOURCE, LASTUPDATEDATE
          

            If Not ddlNo.SelectedIndex = 0 Then

                Dim resDate As Date = Nothing
                DateTime.TryParseExact(ddlNo.SelectedValue, _
     "dd/MM/yyyy", CultureInfo.InvariantCulture, _
         DateTimeStyles.None, resDate)

                'qry = qry.Where(Function(x) x.LASTUPDATEDATE = ddlNo.SelectedValue)
                qry2 = qry2.Where(Function(x) x.IMPORT_DATE = resDate)
            End If

            If Not ddlSource.SelectedIndex = 0 Then
                'qry = qry.Where(Function(x) x.DATASOURCE = ddlSource.SelectedValue
                'Dim qry3 = (From ms In SanctionEntity.MSANCTIONLIST Where ms.LISTTYPECODE = ddlSource.SelectedValue Select ms.LISTTYPENAME).First
                qry2 = qry2.Where(Function(x) x.FILE_TYPE = ddlSource.SelectedValue)
            End If
            'qry = qry.OrderByDescending(Function(fn) fn.LASTUPDATEDATE)
            'qry2 = qry2.Where(Function(x) x.IMPORTID < 50)
            qry2 = qry2.OrderByDescending(Function(fn) fn.IMPORT_DATE).ThenBy(Function(fn2) fn2.DATASOURCE)

            dsMaster.Tables.Add(clsDataTable.LINQToDataTable(qry2, "dsMaster").Copy)

            Dim dtMaster = dsMaster.Tables("dsMaster")
            If dtMaster.Rows.Count > 0 Then
                For Each rowx As DataRow In dtMaster.Rows
                    rowx("LASTUPDATEDATE") = CDate(rowx("IMPORT_DATE")).ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                Next
            End If
            grdIndividual.DataSource = dtMaster
            grdIndividual.DataBind()

            If grdIndividual.Rows.Count = 0 Then
                lblMsg.Visible = True
                lblTotal.Text = ""
            Else
                lblMsg.Visible = False
                lblTotal.Text = "จำนวนรายการทั้งหมด " + dsMaster.Tables("dsMaster").Rows.Count.ToString + " รายการ "
            End If

            clsDataTable = Nothing
        Catch ex As Exception
            WriteError(ex, "IsDataBind", "SanctionHistory")
        End Try
    End Sub

    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

    Private Sub clear()

        dsMaster.Tables("dsMaster").Clear()
        grdIndividual.DataSource = dsMaster.Tables("dsMaster")
        grdIndividual.DataBind()
        clearGvIndex()
        lblMsg.Visible = False
        lblTotal.Text = ""
        ddlSource.SelectedIndex = 0

    End Sub

    Private Sub reset()
        clearGvIndex()
        lblMsg.Visible = False
    End Sub

    Private Sub SaveLog(ByVal index As Integer)
        Try
            Dim program As String = "M73"
            Dim programName As String = " Sanction > ประวัติรายชื่อ Sanction List"

            Dim desc As String = ""
            If index = 1 Then
                desc = "ค้นหา" + programName
            ElseIf index = 2 Then
                desc = "พิมพ์" + programName
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, index, desc, program)


            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region
    Protected Sub ddlSource_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlSource.SelectedIndexChanged
        Try
            'Dim clsDropDown As New clsMasterDropDown
            If Not (ddlSource.SelectedIndex = 0) Then
                'clsDropDown.setLastUpdateDate(ddlNo, ddlSource.SelectedValue)
                setLastUpdateDate(ddlNo, ddlSource.SelectedValue)
            Else
                ddlNo.Items.Clear()
                Dim AddItem As ListItem = Nothing
                AddItem = New ListItem(Resources.resClsMasterDropdown.Select_Search, 0)
                ddlNo.Items.Insert(0, AddItem)
                AddItem = Nothing
            End If
            ' clsDropDown = Nothing
        Catch ex As Exception
            WriteError(ex, "ddlSource_SelectedIndexChanged", "SanctionHistory")
            Throw ex
        End Try
    End Sub

    Sub setLastUpdateDate(ByRef ddlData As DropDownList, Optional ByVal DataSourceValue As String = "")

        ddlData.Items.Clear()

        Dim AddItem As ListItem = Nothing
        Dim dtMaster As New DataTable
        AddItem = New ListItem(Resources.resClsMasterDropdown.Select_Search, 0)

        Dim qryS2 = "select distinct m.info_source,im.import_date , im.importid ,ms.listtypecode,'' as LASTUPDATEDATE" +
                    " from KYCADMIN.amlo_new_master_temp m" +
                    " join KYCADMIN.amlo_new_import_temp im on m.importid = im.importid " +
                    " join KYCADMIN.msanctionlist ms on im.file_type = ms.listtypecode"
        If Not (DataSourceValue = "") Then

            qryS2 += " where ms.listtypecode = '" + DataSourceValue + "'"
        End If

        qryS2 += " order by im.import_date desc"

        dtMaster = clsDatabase.QueryDataTable(qryS2)

        If dtMaster.Rows.Count > 0 Then
            For Each rowx As DataRow In dtMaster.Rows
                rowx("LASTUPDATEDATE") = CDate(rowx("IMPORT_DATE")).ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
            Next
        End If

        ddlData.DataSource = dtMaster
        ddlData.DataTextField = "LASTUPDATEDATE"
        ddlData.DataValueField = "LASTUPDATEDATE"
        ddlData.DataBind()
        ddlData.Items.Insert(0, AddItem)

    End Sub
End Class
